package com.future;

import com.future.util.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution_levelOrderBottom_107 {

    public static void main(String[] args) {
        TreeNode head = new TreeNode(3,
                new TreeNode(4, new TreeNode(99, null, new TreeNode(100)), null),
                new TreeNode(5));
        List<List<Integer>> lists = levelOrderBottom(head);
        for (int i = 0; i < lists.size(); i++) {
            System.out.println(lists.get(i));
        }
    }

    /**
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if (root == null) {
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> curAns = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.poll();
                curAns.add(curNode.val);
                if (curNode.left != null) {
                    // 作为下一层的输出
                    queue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    // 作为下一层的输出
                    queue.offer(curNode.right);
                }
            }
            // 每次插入第一位置，保证最后插进去的排在最前面
            ans.add(0, curAns);
        }
        return ans;
    }
}
